package cn.reinforce.util.http;

import cn.reinforce.util.http.model.HttpResult;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * SEO优化，搜索引擎ping工具
 *
 * @author 幻幻Fate
 * @date 2016-09-06
 * @since 1.0.0
 */
public class PingUtil {

    private static final Logger LOG = LoggerFactory.getLogger(PingUtil.class.getName());


    private PingUtil() {
        super();
    }

    /**
     * 生成ping包
     *
     * @param title    文章标题
     * @param url      网站首页地址
     * @param shareURL 文章底子好
     * @param rssURL   网站rss地址
     * @return
     */
    private static String buildMethodCall(String title, String url,
                                          String shareURL, String rssURL) {
        Document document = DocumentHelper.createDocument();
        Element methodCall = document.addElement("methodCall");
        Element methodName = methodCall.addElement("methodName");
        methodName.addText("weblogUpdates.extendedPing");
        Element params = methodCall.addElement("params");
        params.addElement("param").addElement("value").addElement("string")
                .addText(title);
        params.addElement("param").addElement("value").addElement("string")
                .addText(url);
        params.addElement("param").addElement("value").addElement("string")
                .addText(shareURL);
        params.addElement("param").addElement("value").addElement("string")
                .addText(rssURL == null ? "" : rssURL);
        return document.asXML();
    }

    /**
     * ping搜索引擎
     *
     * @param rpc      搜索引擎的ping地址
     * @param title    文章标题
     * @param url      网站首页地址
     * @param shareURL 文章底子好
     * @param rssURL   网站rss地址
     * @return 搜索引擎返回的结果
     */
    public static boolean ping(String rpc, String title, String url, String shareURL, String rssURL) {
        Map<String, String> headers = new HashMap<>();
        String methodCall = buildMethodCall(title, url, shareURL, rssURL);
        Element root = null;
        try {
            HttpResult httpResult = HttpClientUtil.postByEntity(rpc, methodCall, headers);
            String ret = httpResult.getResult();
            Document document = DocumentHelper.parseText(ret.trim());
            root = document.getRootElement();
        } catch (DocumentException e) {
            LOG.error("内容读取失败", e);
        }

        if (root == null) {
            return false;
        }

        return StringUtils.equals("0", root.element("params").element("param").element("value").element("int").getText());
    }

}
